package com.wph.gulimall.ware.service.impl;

import com.wph.common.constant.WareConstant;
import com.wph.gulimall.ware.entity.PurchaseDetailEntity;
import com.wph.gulimall.ware.service.PurchaseDetailService;
import com.wph.gulimall.ware.service.WareSkuService;
import com.wph.gulimall.ware.vo.MergeVo;
import com.wph.gulimall.ware.vo.PurchaseDoneItemVo;
import com.wph.gulimall.ware.vo.PurchaseDoneVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wph.common.utils.PageUtils;
import com.wph.common.utils.Query;

import com.wph.gulimall.ware.dao.PurchaseDao;
import com.wph.gulimall.ware.entity.PurchaseEntity;
import com.wph.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    PurchaseDetailService purchaseDetailService;

    @Resource
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status",0).or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null){
            //新建一个采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();

        }

        // TODO 确认采购单状态是0，1才可以合并
//        PurchaseEntity flagEntity = this.baseMapper.selectById(purchaseId);
//        if (flagEntity.getStatus()==WareConstant.PurchaseStatusEnum.CREATED.getCode()
//                || flagEntity.getStatus()==WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
//            List<Long> items = mergeVo.getItems();
//            Long finalPurchaseId = purchaseId;
//            List<PurchaseDetailEntity> collect = items.stream().map((id) -> {
//                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
//                purchaseDetailEntity.setId(id);
//                purchaseDetailEntity.setPurchaseId(finalPurchaseId);
//                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
//                return purchaseDetailEntity;
//            }).collect(Collectors.toList());
//
//            //批量修改
//            purchaseDetailService.updateBatchById(collect);
//
//            PurchaseEntity purchaseEntity = new PurchaseEntity();
//            purchaseEntity.setUpdateTime(new Date());
//            purchaseEntity.setId(purchaseId);
//            this.updateById(purchaseEntity);
//        }else {
//            log.error("此订单已被领取或已完成");
//        }

        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map((id) -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(id);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        //批量修改
        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setId(purchaseId);
        this.updateById(purchaseEntity);
    }

    /**
     *
     * @param ids  采购单id
     */
    @Transactional
    @Override
    public void received(List<Long> ids) {
        //1、确认采购单是新建或者是已分配状态
        List<PurchaseEntity> collect = ids.stream().map((id) -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
            //过滤状态是新建或者已分配的采购单出来
        }).filter((entity -> {
            return entity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    || entity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
            //更改需要领取的采购单状态，以便后面进行数据库的真正改变
        })).map(item->{
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        //2、改变采购单的状态
        this.updateBatchById(collect);

        //3、改变采购需求采购项的状态
        collect.forEach((item)->{
            List<PurchaseDetailEntity> entities = purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> detailEntities = entities.stream().map((entity) -> {
                //下面这样就只更新这两个字段，如果直接用entity来做更新，更新的字段就太多了（这些更新的都是没有必要更新的）
                PurchaseDetailEntity entity1 = new PurchaseDetailEntity();
                entity1.setId(entity.getId());
                entity1.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return entity1;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(detailEntities);
        });

    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {

        Long id = doneVo.getId();

        //2、改变采购项的状态
        Boolean flag = true;
        List<PurchaseDoneItemVo> items = doneVo.getItems();

        ArrayList<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseDoneItemVo item : items){
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;
                //detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());//和下面等价
                detailEntity.setStatus(item.getStatus());
            }else {
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());

                //3、将成功采购的进行入库
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(updates);

        //1、改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode()
                :WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);


    }
}